<template>
  <!-- 模态框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginbox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- 导航 -->
      <nav class="nav">
        <a
          href="javascript:;"
          :class="{ active: isShowPhoneLogin }"
          @click="isShowPhoneLogin = true"
          >手机号码登录</a
        >
        |
        <a
          href="javascript:;"
          @click="showQr"
          :class="{ active: !isShowPhoneLogin }"
          >微信扫码登录</a
        >
      </nav>
      <!-- 导航对应的内容区 -->
      <div class="content">
        <!-- 手机号登录 -->
        <div class="phoneLogin" v-show="isShowPhoneLogin">
          <div class="row">
            <input type="text" placeholder="请输入手机号" v-model="phoneNum" />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model="yzmcode"
            />
            <button class="getmsg btn" @click="getcode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="getmsg btn" v-show="isShowCount">
              {{ count + " s" }}
            </button>
          </div>
          <div class="row">
            <button class="loginBtn btn" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信扫码登录 -->
        <!-- 显示微信二维码第二步: 提供显示二维码的容器id -->
        <div class="wxLogin" v-show="!isShowPhoneLogin" id="weixin">
          微信扫码登录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { SendSMSAPI, PhoneReginAPI, BindingApi } from "../request/api.js";
import { validatePhoneNumber } from "@/utils";
export default {
  data() {
    return {
      isShowPhoneLogin: true,
      msg: "向右滑动",
      // 手机号
      phoneNum: "",
      // 倒计时
      count: 60,
      // 控制倒计时是否显示
      isShowCount: false,
      // 验证码
      yzmcode: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogined: "loginStatus/changeIsLogined",
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncShowToast: "showToast/asyncShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 获取验证码
    async getcode() {
      // 1.2 调用toVerify进行校验, 如果校验通过了, 继续判断3, 否则return 不执行3
      let flag = this.toVerify();
      if (!flag) return;
      // 3. 开始获取验证码 (请求后台发送验证码),发送成功后, 进行倒计时功能
      // console.log("验证通过了...");
      let res = await SendSMSAPI({
        phone: this.phoneNum.trim(),
      });
      // console.log("短信,", res);
      //   拦截器已经报错了,也就是没有必要再判断==0情况了
      if (!res) return;
      //   成功的场景
      if (res.code == 0) {
        // 倒计时功能
        this.isShowCount = true;
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            // 停止定时器
            clearInterval(timer);
            this.count = 60;
            this.isShowCount = false;
          }
        }, 1000);
      }
    },
    // 统一校验手机号和滑块验证码
    toVerify() {
      // 1. 判断手机号 是否输入正确, 不正确就提示
      if (!validatePhoneNumber(this.phoneNum)) {
        // 显示出提示框组件, 并自动隐藏
        this.asyncShowToast({
          isShow: true,
          title: "请输入正确的手机号码!",
          type: "danger",
        });
        return;
      }
      //   2. 判断滑块验证码,是否输入正确, 不正确就提示
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        // 直接删除changeIsShowToast 缓存actions方法
        this.asyncShowToast({
          isShow: true,
          title: "请完成滑块验证码!",
          type: "danger",
        });
        return;
      }
      // 走到这说明通过了
      return true;
    },
    // 登录
    async submitFn() {
      // 1.2 调用toVerify进行校验, 如果校验通过了, 继续判断3, 否则 return 不执行3
      if (!this.toVerify()) return;
      // 3. 判断短信验证码是否正确, (因为后端没有返回手机号那个验证码, 此处只判断非空) v-model
      if (this.yzmcode == "") {
        this.asyncShowToast({
          isShow: true,
          title: "请输入短信验证码!",
          type: "danger",
        });
        return;
      }
      // 4. 发起登录请求
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        // 如果有uuid则是手机绑定微信-登录请求
        res = await BindingApi({
          verifyCode: this.yzmcode,
          phone: this.phoneNum,
          uuid,
        });
      } else {
        res = await PhoneReginAPI({
          verifyCode: this.yzmcode,
          phone: this.phoneNum,
        });
      }

      if (!res) return;
      if (res.code == 0) {
        // console.log("登录成功", res);
        // 1.提示登录成功
        this.asyncShowToast({
          isShow: true,
          title: "登录成功!",
          type: "success",
        });
        // 2. 存储token, 后面发请求时需要用到 localStorage setItem() getItem()
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        // 3. 隐藏登录框
        this.changeIsShowLoginModal(false);
        // 4. 更新登录状态 (已登录显示 购物车按钮, 未登录显示 登录按钮)
        this.changeIsLogined(true);
        // 5. 清除uuid
        localStorage.removeItem("uuid");
        // 登录成功后, 调用actions方法更新用户信息
        this.asyncChangeUserInfo();
      }
    },
    // 显示微信二维码
    showQr() {
      this.isShowPhoneLogin = false;
      // 显示微信二维码第三步: 实例化WxLogin
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQouaW1wb3dlckJveCBxcmNvZGUgew0KICAgIG1hcmdpbi10b3A6IDIwcHg7DQp9DQo=",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;

  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .loginbox {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");

    .close {
      background: url("../assets/img/close.png");
      width: 22px;
      height: 22px;
      position: absolute;
      top: 10px;
      right: 58px;
      cursor: pointer;
    }

    .nav {
      margin-top: 45px;
      text-align: center;
      font-size: 18px;
      color: #ccc;

      a {
        text-decoration: none;
        color: #ccc;

        &.active {
          color: #000;
        }
      }
    }

    .content {
      width: 355px;
      margin: 20px auto;

      .row {
        display: flex;
        margin-bottom: 20px;

        input {
          flex: 1;
          height: 50px;
          text-indent: 1em;
          outline: none;
        }

        .btn {
          background-color: #0a328e;
          color: #eee;
          font-size: 14px;
          border: none;
          cursor: pointer;
        }

        .getmsg {
          margin-left: 10px;
          width: 90px;
        }

        .loginBtn {
          height: 50px;
          flex: 1;
        }
      }
      .wxLogin {
        text-align: center;
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;

  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }

  .slide-verify-block {
    width: 85px;
    height: 136px;
  }

  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }

  &:hover {
    canvas {
      display: block;
    }

    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>